﻿package ac.java.utils;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

public class AcHttp {
	public static String getQueryParam(Map<String,Object> paramMap){
		StringBuffer sb = new StringBuffer();
		if(paramMap.isEmpty()){
			return "" ;
		}else{
			for(String key: paramMap.keySet()){
				String value = (String)paramMap.get(key);
				if(sb.length()<1){
					sb.append(key).append("=").append(value);
				}else{
					sb.append("&").append(key).append("=").append(value);
				}
			}
			return sb.toString();
		}
	}
	
	public static String post(String urlAddress,Map paramMap)
	{
		StringBuilder rs = null;
		URL url = null;
		HttpURLConnection httpUrlConnection = null;
		try {
			url = new URL(urlAddress);
			httpUrlConnection = (HttpURLConnection) url.openConnection();
			httpUrlConnection.setDoInput(true);
			httpUrlConnection.setDoOutput(true);

			httpUrlConnection.setRequestMethod("POST");
			httpUrlConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");

			//String username = "ip=192.168.0.1";
			String queryString = AcHttp.getQueryParam(paramMap);
			httpUrlConnection.getOutputStream().write(queryString.getBytes());

			httpUrlConnection.getOutputStream().flush();
			httpUrlConnection.getOutputStream().close();
			int code = httpUrlConnection.getResponseCode();

			if (code == 200) {
				// 发送Cookie
				String cookie = httpUrlConnection.getHeaderField("Set-Cookie");
				if(null != cookie && !cookie.equals(""))
				{
					httpUrlConnection.setRequestProperty("Cookie", cookie);
				}
				
				InputStreamReader inputStreamReader = new InputStreamReader(httpUrlConnection.getInputStream());
				BufferedReader in = new BufferedReader(inputStreamReader);
				
			    String line = null;  
			    rs = new StringBuilder();  
			    while ((line = in.readLine()) != null) {  
			      rs.append(line);  
			    }
			    
			    in.close();
			    inputStreamReader.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (httpUrlConnection != null) {
				httpUrlConnection.disconnect();
			}
		}
		
		if(null == rs)
		{
			return null;
		}
		
		return rs.toString();
	}
	
	
}
